<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
<!--      <el-form-item label="客户编号" prop="customerNumber">-->
<!--        <el-input-->
<!--            v-model="queryParams.customerNumber"-->
<!--            placeholder="请输入客户编号"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="客户名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactPerson" style="width:240px;">
        <el-input
            v-model="queryParams.contactPerson"
            placeholder="请输入联系人姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="联系人职位" prop="position">-->
<!--        <el-input-->
<!--            v-model="queryParams.position"-->
<!--            placeholder="请输入联系人职位"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="联系电话" prop="phone">-->
<!--        <el-input-->
<!--            v-model="queryParams.phone"-->
<!--            placeholder="请输入联系电话"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="电子邮箱" prop="email">-->
<!--        <el-input-->
<!--            v-model="queryParams.email"-->
<!--            placeholder="请输入电子邮箱"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="省份" prop="province">-->
<!--        <el-input-->
<!--            v-model="queryParams.province"-->
<!--            placeholder="请输入省份"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="城市" prop="city">-->
<!--        <el-input-->
<!--            v-model="queryParams.city"-->
<!--            placeholder="请输入城市"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="区县" prop="district">-->
<!--        <el-input-->
<!--            v-model="queryParams.district"-->
<!--            placeholder="请输入区县"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="开户行" prop="bankName">-->
<!--        <el-input-->
<!--            v-model="queryParams.bankName"-->
<!--            placeholder="请输入开户行"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="银行账号" prop="bankAccount">-->
<!--        <el-input-->
<!--            v-model="queryParams.bankAccount"-->
<!--            placeholder="请输入银行账号"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="创建人" prop="createdBy">-->
<!--        <el-input-->
<!--            v-model="queryParams.createdBy"-->
<!--            placeholder="请输入创建人"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeCreatedAt"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
<!--      <el-form-item label="修改人" prop="updatedBy">-->
<!--        <el-input-->
<!--            v-model="queryParams.updatedBy"-->
<!--            placeholder="请输入修改人"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="修改时间" style="width: 308px">-->
<!--        <el-date-picker-->
<!--            v-model="daterangeUpdatedAt"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            type="daterange"-->
<!--            range-separator="-"-->
<!--            start-placeholder="开始日期"-->
<!--            end-placeholder="结束日期"-->
<!--        ></el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['SysSales:SysSalesCustomers:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['SysSales:SysSalesCustomers:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['SysSales:SysSalesCustomers:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['SysSales:SysSalesCustomers:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SysSalesCustomersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="customerId" width="80" />
      <el-table-column label="客户编号" align="center" prop="customerNumber" />
      <el-table-column label="客户名称" align="center" prop="name" />
      <el-table-column label="客户类型" align="center" prop="type" />
      <el-table-column label="联系人姓名" align="center" prop="contactPerson" />
<!--      <el-table-column label="联系人职位" align="center" prop="position" />-->
<!--      <el-table-column label="联系电话" align="center" prop="phone" />-->
<!--      <el-table-column label="电子邮箱" align="center" prop="email" />-->
      <el-table-column label="省份" align="center" prop="province" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="区县" align="center" prop="district" />
      <el-table-column label="详细地址" align="center" prop="address" :show-overflow-tooltip="true" />
<!--      <el-table-column label="开户行" align="center" prop="bankName" :show-overflow-tooltip="true"/>-->
<!--      <el-table-column label="银行账号" align="center" prop="bankAccount" :show-overflow-tooltip="true"/>-->
<!--      <el-table-column label="客户状态" align="center" prop="status" />-->
<!--      <el-table-column label="创建人" align="center" prop="createdBy" />-->
<!--      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="修改人" align="center" prop="updatedBy" />-->
<!--      <el-table-column label="修改时间" align="center" prop="updatedAt" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleOrderDetail(scope.row)" v-hasPermi="['SysSales:SysSalesCustomers:remove']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" style="margin-left: 2px" v-hasPermi="['SysSales:SysSalesCustomers:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" style="margin-left: 2px" v-hasPermi="['SysSales:SysSalesCustomers:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="SysSalesCustomersRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="客户名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户编号" prop="customerNumber">
              <el-input v-model="form.customerNumber" placeholder="请输入客户编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="客户类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择客户类型" clearable>
                <el-option label="批发商" value="批发商" />
                <el-option label="零售商" value="零售商" />
                <el-option label="个人消费者" value="个人消费者" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactPerson" label-width="82px" style="margin-left: -2px">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="联系人职位" prop="position" label-width="82px" style="margin-left: -2px">
              <el-input v-model="form.position" placeholder="请输入联系人职位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-input v-model="form.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-input v-model="form.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区县" prop="district">
              <el-input v-model="form.district" placeholder="请输入区县" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="开户行" prop="bankName">
          <el-input v-model="form.bankName" placeholder="请输入开户行" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog :title="orderTitle" v-model="orderOpen" width="800px" append-to-body>
      <el-table :data="orderList" style="width: 100%" :span-method="mergeCells" border>
        <el-table-column label="产品名称" align="center" prop="name" />
        <el-table-column label="产品数量" align="center" prop="totalQuantity" />
        <el-table-column label="成交总量" align="center" prop="totalSum" />
      </el-table>

      <!-- 添加求和显示 -->
      <div style="margin-top: 10px; text-align: right;">
        <span>产品数量合计：</span>
        <strong>{{ getTotalQuantity() }}</strong>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="orderOpen = false">确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="SysSalesCustomers">
import { listSysSalesCustomers, getSysSalesCustomers, delSysSalesCustomers, addSysSalesCustomers, updateSysSalesCustomers,getProductCount} from "@/api/SysSales/SysSalesCustomers"
// import { listSysSalesOrders } from "@/api/SysSales/SysSalesOrders"
const { proxy } = getCurrentInstance()

const SysSalesCustomersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeCreatedAt = ref([])
const daterangeUpdatedAt = ref([])
const orderOpen = ref(false)
const orderList = ref([])
const orderTitle = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerNumber: null,
    name: null,
    type: null,
    contactPerson: null,
    position: null,
    phone: null,
    email: null,
    province: null,
    city: null,
    district: null,
    address: null,
    bankName: null,
    bankAccount: null,
    status: null,
    createdBy: null,
    createdAt: null,
    updatedBy: null,
    updatedAt: null
  },
  rules: {
    customerNumber: [
      { required: true, message: "客户编号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "客户名称不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "客户类型不能为空", trigger: "change" }
    ],
    phone: [
      // { required: true, message: "联系电话不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    email: [
      // { required: true, message: "电子邮箱不能为空", trigger: "blur" },
      { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 合并单元格方法 */
function mergeCells({ row, column, rowIndex, columnIndex }) {
  // 只对成交总量列进行合并
  if (columnIndex === 2) { // 成交总量列
    // 获取当前行的成交总量值
    const currentTotal = row.totalSum;

    // 查找相同成交总量值的连续行数
    let count = 1;
    for (let i = rowIndex + 1; i < orderList.value.length; i++) {
      if (orderList.value[i].totalSum === currentTotal) {
        count++;
      } else {
        break;
      }
    }

    return {
      rowspan: count,
      colspan: 1
    }
  }

  // 其他列不合并，保持原有布局
  return {
    rowspan: 1,
    colspan: 1
  }
}

/** 查询客户信息列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreatedAt && '' != daterangeCreatedAt) {
    queryParams.value.params["beginCreatedAt"] = daterangeCreatedAt.value[0]
    queryParams.value.params["endCreatedAt"] = daterangeCreatedAt.value[1]
  }
  if (null != daterangeUpdatedAt && '' != daterangeUpdatedAt) {
    queryParams.value.params["beginUpdatedAt"] = daterangeUpdatedAt.value[0]
    queryParams.value.params["endUpdatedAt"] = daterangeUpdatedAt.value[1]
  }
  listSysSalesCustomers(queryParams.value).then(response => {
    SysSalesCustomersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    customerId: null,
    customerNumber: null,
    name: null,
    type: null,
    contactPerson: null,
    position: null,
    phone: null,
    email: null,
    province: null,
    city: null,
    district: null,
    address: null,
    bankName: null,
    bankAccount: null,
    status: null,
    createdBy: null,
    createdAt: null,
    updatedBy: null,
    updatedAt: null
  }
  proxy.resetForm("SysSalesCustomersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreatedAt.value = []
  daterangeUpdatedAt.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.customerId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加客户信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _customerId = row.customerId || ids.value
  getSysSalesCustomers(_customerId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改客户信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["SysSalesCustomersRef"].validate(valid => {
    if (valid) {
      if (form.value.customerId != null) {
        updateSysSalesCustomers(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSysSalesCustomers(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _customerIds = row.customerId || ids.value
  proxy.$modal.confirm('是否确认删除客户信息编号为"' + _customerIds + '"的数据项？').then(function() {
    return delSysSalesCustomers(_customerIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('SysSales/SysSalesCustomers/export', {
    ...queryParams.value
  }, `SysSalesCustomers_${new Date().getTime()}.xlsx`)
}

/** 查询订单列表 */
// function getOrderList(customerId) {
//   // const params = {
//   //   customerId: customerId,
//   //   pageNum: 1,
//   //   pageSize: 100
//   // }
//   // console.log("params",params)
//   // listSysSalesOrders(params).then(response => {
//   //   console.log("response",response)
//   //   orderList.value = response.rows
//   //   // 按订单日期排序
//   //   orderList.value.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
  // })
  // console.log("customerId",customerId)
  // getProductCount(customerId).then(response => {
  //   console.log("response",response)
  //   orderList.value = response.rows
  // })
// }

/** 查看订单详情 */
function handleOrderDetail(row) {
  orderTitle.value = "客户订单详情"
  orderOpen.value = true
  console.log("customerId",row.customerId)
  getProductCount(row.customerId).then(response => {
    console.log("response",response)
    orderList.value = response.rows
  })
}

/** 计算产品数量总和 */
function getTotalQuantity() {
  return orderList.value.reduce((sum, item) => sum + (item.totalQuantity || 0), 0)
}

getList()
</script>
}